(function () {
    'use strict';

    angular.module('BlurAdmin.pages.active')
        .controller('listCtrl', WizardCtrl);

    /** @ngInject */
    function WizardCtrl($scope,$http,FileUploader,$timeout,$filter,uibPaginationConfig,$uibModal) {

        console.log(getCookie('nUserId'),getCookie('strTokenId'));
        var $ctrl = this;
        //angular模态框
        $scope.open = function (page, size) {
            $uibModal.open({
                animation: true,
                templateUrl: page,
                controllerAs: $ctrl,
                scope : $scope,
                size: size
            });
        };

        // 初始化分页信息
        uibPaginationConfig.previousText = '上一页';
        uibPaginationConfig.nextText = '下一页';

        //默认加载一页条数
        $scope.listPage = 1;
        $scope.listSize = 10;

        //最大时间
        $scope.dates = {
            Start : '',
            End : '',
            EventCategory : '',
            IsPublic : '-1',
            StartTxt : '请选择开始时间',
            EndTxt : '请选择结束时间'
        };

        //设置时间的时候,选取的时间发生改变时
        $scope.onTimeSet = {
            start : function (newDate,oldDate) {
                $scope.dates.StartTxt = $filter('date')(newDate, 'yyyy-MM-dd');
            },
            end : function (newDate,oldDate) {
                $scope.dates.EndTxt = $filter('date')(newDate, 'yyyy-MM-dd');
            },
            add_start : function (newDate,oldDate) {
                $scope.lists.StartTxt = $filter('date')(newDate, 'yyyy-MM-dd HH:mm');
                console.log($scope.lists.StartTxt);
            },
            add_end : function (newDate,oldDate) {
                $scope.lists.EndTxt = $filter('date')(newDate, 'yyyy-MM-dd HH:mm');
                console.log($scope.lists.EndTxt);
            }
        }

        // 请求页面列表数据
        function loadData() {
            var postData = {
                nCurPage : $scope.listPage,
                nPageSize : $scope.listSize
            };
            if($scope.dates.Start){
                postData.StartDate = $scope.dates.StartTxt;
            }
            if($scope.dates.End){
                postData.EndDate = $scope.dates.EndTxt;
            }
            if($scope.dates.EventCategory){
                postData.EventCategory = $scope.dates.EventCategory;
            }
            if($scope.dates.IsPublic){
                postData.IsPublic = $scope.dates.IsPublic;
            }
            $http({
                method:'POST',
                url : $config.host+'/api/events/GetEventList',
                data : $config.urlCode(postData)
            }).success(function (json) {
                if(json.isSuccess == true){
                    $scope.jsons = json.data;
                    //设置分页总条数
                    $scope.totalItems = json.recordsFiltered;
                    //分页点击显示个数
                    $scope.maxSize = 6;
                    getActiveType();
                }
            })
        }
        // 初始化活动列表
        loadData();

        //选择分页的时候
        $scope.pageChanged = function(value) {
            $scope.listPage = value;
            console.log(0)
            loadData();
        };

        //选择每页显示条数的时候
        $scope.sizeChanged = function(value) {
            $scope.listSize = value;
            console.log(1)
            loadData();
        };

        //点击查询进行筛选
        $scope.screenList =function () {
            if($scope.dates.Start&&!$scope.dates.End){
                $scope.isPrompt('请选择结束时间！');
                return;

            }
            if(!$scope.dates.Start&&$scope.dates.End){
                $scope.isPrompt('请选择开始时间！');
                return;
            }
            if($scope.dates.End<$scope.dates.Start){
                $scope.isPrompt('结束时间请选在开始时间之后！');
                return;
            }
            loadData();
        }

        // 获取活动类型列表，转化活动类型文字
        function getActiveType() {
            //活动类型转换成文字
            function typeFilver() {
                //设置活动类型显示文字
                angular.forEach($scope.jsons,function (all) {
                    all.EventCategoryTxt = '没有该活动类型';
                    angular.forEach($scope.activeType,function (value) {
                        if(all.EventCategory==value.nCategoryId){
                            all.EventCategoryTxt = value.strCategoryName;
                        }
                    })
                })
            }
            if($scope.activeType){
                typeFilver();
            }else{
                //活动类型列表赋值
                $http({
                    method:'POST',
                    url : $config.host+'/api/events/GetCateGory'
                }).success(function (json) {
                    if(json.isSuccess){
                        $scope.activeType = json.data;
                        typeFilver();
                    }
                });
            }
        }

        //弹出prompt框
        $scope.isPrompt = function (value,isConfirm,title) {
            $scope.showPrompt = value;
            if(title){
                $scope.promptTitle = title;
            }else{
                $scope.promptTitle = '温馨提示';
            }
            if(isConfirm){
                $scope.isConfirmShow = true;
            }else{
                $scope.isConfirmShow = false;
            }
            $scope.open('/app/pages/active/list/modal/prompt.html','sm');
        }

        //点击删除按钮
        $scope.deleteList = function (eid) {
            $scope.promptTitle = '删除';
            $scope.isPrompt('您确定删除这条记录吗？',true);
            $scope.EventId = eid;
            console.log(eid);
            //点击确定删除按钮
            $scope.confirmPrompt = function () {
                $http({
                    method:'POST',
                    // url : $config.host+'/api/Events/DelEvent',
                    url : $config.host+'/api/Events/BatchDelEvent',
                    headers:{
                        UID :getCookie('nUserId'),
                        TOKENID : getCookie('strTokenId')
                    },
                   /* data : $config.urlCode({
                        nEventId : eid
                    })*/
                    params:{
                        strEventId : eid
                    }
                }).success(function (json) {
                    if(json.isSuccess == true){
                        $scope.isPrompt(json.message);
                        loadData();
                    }
                })
            }
        }

        //勾选所有列表
        $scope.choiceAllList = function () {
            var boole = true;
            angular.forEach($scope.jsons,function (value,key) {
                if(!value.choosed){
                    boole = false;
                }else{
                    boole = true;
                }
            })
            angular.forEach($scope.jsons,function (value,key) {
                if(boole){
                    value.choosed = false;
                }else{
                    value.choosed = true;
                }
            })
        }

        //点击批量删除按钮
        $scope.openPromptbig =function () {
            $scope.promptTitle = '批量删除';
            $scope.isPrompt('您确定删除选中记录吗？',true);
            var choiceArray = '';
            angular.forEach($scope.jsons,function (value,key) {
                if(value.choosed){
                    choiceArray+= value.EventId.toString()+',';
                }
            })
            choiceArray = choiceArray.substring(0,choiceArray.length-1);
            console.log('删除的数组Id',choiceArray);
            //点击确定删除按钮
            $scope.confirmPrompt = function () {
                $http({
                    method:'POST',
                    url : $config.host+'/api/Events/BatchDelEvent',
                    headers:{
                        UID :getCookie('nUserId'),
                        TOKENID : getCookie('strTokenId')
                    },
                    // data : $config.urlCode({
                    //     nEventId : choiceArray
                    // })
                    params:{
                        strEventId : choiceArray
                    }
                }).success(function (json) {
                    if(json.isSuccess){
                        $scope.isPrompt(json.message);
                        loadData();
                    }
                })
            }
        }



        //添加和修改列表数据
        $scope.modalListFunc = function (type,index,eventid) {
            //打开模态框-大型
            $scope.open('/app/pages/active/list/modal/add-put.html','lg');
            if(type=='add'){
                //新增数据初始化
                $scope.lists = {
                    modelTitle : '增加',
                    EventName : '',
                    Address : '',
                    Longitude : '',
                    Latitude : '',
                    StartDate : '',
                    EndDate : '',
                    MemberCount : '',
                    ChargeType : false,
                    EventCost : '',
                    Details : '',
                    Summary : '',
                    IsPublic : true,
                    EventCategory : '',
                    StartTxt:'请选择活动开始时间',
                    EndTxt:'请选择活动结束时间'
                }
                //点击确认按钮
                $scope.lists.submitModel = function () {
                    if(!formVerity()) return;
                    if($scope.lists.EventCategory == 1){
                        $scope.lists.IsChoice = true;
                    }else{
                        $scope.lists.IsChoice = false;
                    }
                    console.log($scope.lists.EventCategory,$scope.lists.IsChoice);
                    //请求增加接口
                    $http({
                        method:'POST',
                        url : $config.host+'/api/Events/OptEvent',
                        headers:{
                            UID :getCookie('nUserId'),
                            TOKENID : getCookie('strTokenId')
                        },
                        params:{
                            Opt : 'Add',
                            UserId : getCookie('nUserId'),
                            EventName : $scope.lists.EventName,
                            Address : $scope.lists.Address,
                            Longitude : $scope.lists.Longitude,
                            Latitude : $scope.lists.Latitude,
                            MemberCount : $scope.lists.MemberCount,
                            ChargeType : $scope.lists.ChargeType,
                            EventCost : $scope.lists.EventCost,
                            Summary : $scope.lists.Summary,
                            Details : $scope.lists.Details,
                            StartDate : $scope.lists.StartTxt,
                            EndDate : $scope.lists.EndDate,
                            EventCategory : $scope.lists.EventCategory,
                            isChoice : $scope.lists.IsChoice,
                            IsPublic : $scope.lists.IsPublic,
                            CityName : $scope.lists.CityName
                        }
                    }).success(function (json) {
                        if(json.isSuccess == true){
                            $scope.isPrompt(json.message);
                            loadData();
                        }
                    })
                }
            }else if(type=='put'){
                var $json = $scope.jsons[index];
                $scope.lists = {
                    modelTitle : '修改',
                    EventName : $json.EventName,
                    Address : $json.Address,
                    Longitude : $json.Longitude,
                    Latitude : $json.Latitude,
                    MemberCount : $json.MemberCount,
                    ChargeType : $json.ChargeType,
                    EventCost : $json.EventCost,
                    Summary : $json.Summary,
                    Details : $json.Details,
                    StartDate : $json.StartDate,
                    EndDate : $json.EndDate,
                    EventCategory : $json.EventCategory,
                    isChoice : $json.IsChoice,
                    IsPublic : $json.IsPublic,
                    CityName : $json.CityName,
                    StartTxt : $filter('date')($json.StartDate, 'yyyy-MM-dd HH:mm'),
                    EndTxt : $filter('date')($json.EndDate, 'yyyy-MM-dd HH:mm')
                }
                console.log($scope.lists);
                //对比是否有修改
                var valiteData = JSON.stringify($scope.lists);
                //点击确认按钮
                $scope.lists.submitModel = function () {
                    //对比是否有修改
                    if(valiteData === JSON.stringify($scope.lists)){
                        $scope.isPrompt('您未做任何修改！');
                        return;
                    }
                    if($scope.lists.EventCategory == 1){
                        $scope.lists.IsChoice = true;
                    }else{
                        $scope.lists.IsChoice = false;
                    }
                    // console.log($scope.lists.EventCategory,$scope.lists.IsChoice);
                    //请求修改接口
                    $http({
                        method:'POST',
                        url : $config.host+'/api/Events/OptEvent',
                        headers:{
                            UID :getCookie('nUserId'),
                            TOKENID : getCookie('strTokenId')
                        },
                        params:{
                            Opt : 'Update',
                            UserId : getCookie('nUserId'),
                            EventId : eventid,
                            EventName : $scope.lists.EventName,
                            Address : $scope.lists.Address,
                            Longitude : $scope.lists.Longitude,
                            Latitude : $scope.lists.Latitude,
                            MemberCount : $scope.lists.MemberCount,
                            ChargeType : $scope.lists.ChargeType,
                            EventCost : $scope.lists.EventCost,
                            Summary : $scope.lists.Summary,
                            Details : $scope.lists.Details,
                            StartDate : $scope.lists.StartTxt,
                            EndDate : $scope.lists.EndDate,
                            EventCategory : $scope.lists.EventCategory,
                            isChoice : $scope.lists.IsChoice,
                            IsPublic : $scope.lists.IsPublic,
                            CityName : $scope.lists.CityName
                        }
                    }).success(function (json) {
                        if(json.isSuccess == true){
                            $scope.isPrompt(json.message);
                            loadData();
                        }else{
                            $scope.isPrompt(json.message);
                        }

                    })
                }
            }
        }

        //表单验证
        function formVerity() {
            if(!$scope.lists.EventName){
                $scope.isPrompt('活动名称不能为空！');
                return false;
            }
            if(!$scope.lists.Address){
                $scope.isPrompt('活动地址不能为空！');
                return false;
            }
            if(!$scope.lists.Longitude){
                $scope.isPrompt('活动经度不能为空！');
                return false;
            }
            if(!$scope.lists.Latitude){
                $scope.isPrompt('活动纬度不能为空！');
                return false;
            }
            if(!$scope.lists.StartDate){
                $scope.isPrompt('请选择活动开始时间！');
                return false;
            }
            if(!$scope.lists.EndDate){
                $scope.isPrompt('请选择活动结束时间！');
                return false;
            }
            if($scope.lists.EndDate<$scope.lists.StartDate){
                $scope.isPrompt('结束时间请选在开始时间之后！');
                return;
            }
            if(!$scope.lists.MemberCount){
                $scope.isPrompt('活动人数不能为空！');
                return false;
            }
            if($scope.lists.ChargeType){
                if(!$scope.lists.EventCost){
                    $scope.isPrompt('活动价格不能为空！');
                    return false;
                }
            }
            if(!$scope.lists.Details){
                $scope.isPrompt('活动详情不能为空！');
                return false;
            }
            if(!$scope.lists.Summary){
                $scope.isPrompt('活动简介不能为空！');
                return false;
            }
            if(!$scope.lists.EventCategory){
                $scope.isPrompt('请选择活动类型！');
                return false;
            }
            return true;
        }

        //初始化图片上传
        var uploader = $scope.uploader = new FileUploader();
        //上传图片格式
        uploader.filters.push({
            name: 'imageFilter',
            fn: function(item /*{File|FileLikeObject}*/, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
            }
        });
        //添加一张图片
        uploader.onAfterAddingFile = function(fileItem) {
            // console.info('onAfterAddingFile', fileItem);
            var reader = new FileReader();
            //加载base64
            reader.onload = function () {
                // console.log(reader);
                $scope.$apply(function () {
                    cropImgInit();
                    $scope.cropImg.imgurl = reader.result;
                    // $scope.open('/app/pages/active/list/cropimg.html','lg');
                    //打开裁剪框
                    $scope.cropImgOpen = $uibModal.open({
                        animation: true,
                        templateUrl: '/app/pages/active/list/modal/crop-img.html',
                        controllerAs: $ctrl,
                        scope : $scope,
                        size: 'lg'
                    });
                })
            };
            reader.readAsDataURL(fileItem._file);

        };

        // 初始化封面图片参数
        $scope.modalCoverImg = function (title,listId,type) {

            $scope.imgPage = {
                page : 1,
                size : 10,
                maxSize : 5
            }

            $scope.open('/app/pages/active/list/modal/cover-img.html','lg');
            //设置全局变量，为封面图片上传
            $scope.coverImg = {
                title : title,
                type : type, //有act,cov
                listId: listId,
                upload: function () {
                    $('#coverImgupload').click();
                },
                imgGroup : []
            };

            if($scope.coverImg.type == 'act'){
                activityImglist();

                //点击删除活动图片
                $scope.deleteactivityImg = function (id) {
                    console.log(id);
                    $scope.isPrompt('你确认删除这张图片吗？',true);
                    $scope.confirmPrompt =function () {
                        //点击确定按钮再去请求
                        $http({
                            method:'POST',
                            url : $config.host+'/api/events/BatchDelEventPhoto',
                            headers:{
                                UID :getCookie('nUserId'),
                                TOKENID : getCookie('strTokenId')
                            },
                            params:{
                                EventId : $scope.coverImg.listId,
                                pids :id
                            }
                        }).success(function (json) {
                            if(json.isSuccess){
                                $scope.isPrompt(json.message);
                                activityImglist();
                            }else{
                                $scope.isPrompt(json.message);
                            }
                        })
                    }
                };

            }
            else if($scope.coverImg.type == 'cov'){
                //初始化
                console.log($scope.coverImg.listId)
                coverImglist();

                //点击设为首张
                $scope.sethomePage = function (id,url) {
                    console.log(id);
                    //请求
                    $http({
                        method:'POST',
                        url : $config.host+'/api/events/SetCoverPhoto',
                        headers:{
                            UID :getCookie('nUserId'),
                            TOKENID : getCookie('strTokenId')
                        },
                        params:{
                            EventId : $scope.coverImg.listId,
                            Id :id
                        }
                    }).success(function (json) {
                        if(json.isSuccess){
                            $scope.isPrompt(json.message);
                            coverImglist();
                            //遍历数组赋值
                            angular.forEach($scope.jsons,function (value,key) {
                                // console.log(value,key,value.EventId,$scope.coverImg.listId,value.CoverImg,url);
                                if(value.EventId == $scope.coverImg.listId){
                                    value.CoverImg = url;
                                }
                            })
                        }else{
                            $scope.isPrompt(json.message);
                        }
                    })
                }

                //点击删除封面图片
                $scope.deletecoverImg = function (id,isCover,url) {
                    $scope.isPrompt('你确认删除这张图片吗？',true);
                    console.log(id);
                    console.log(isCover);
                    console.log(url);
                    var postData = {
                        EventId : $scope.coverImg.listId,
                        Ids :id
                    }
                    if(isCover==1){
                        postData.CoverId = id;
                    }
                    $scope.confirmPrompt = function () {
                        //点击确定去请求
                        $http({
                            method:'POST',
                            url : $config.host+'/api/events/BatchDelCover',
                            headers:{
                                UID :getCookie('nUserId'),
                                TOKENID : getCookie('strTokenId')
                            },
                            params:postData
                        }).success(function (json) {
                            if(json.isSuccess){
                                $scope.isPrompt(json.message);
                                coverImglist();
                                console.log(isCover);
                                if(isCover==1){
                                    //遍历数组赋值
                                    angular.forEach($scope.jsons,function (value,key) {
                                        // console.log(value,key,value.EventId,$scope.coverImg.listId,value.CoverImg,null);
                                        if(value.EventId == $scope.coverImg.listId){
                                            value.CoverImg = '';
                                        }
                                    })
                                }
                            }else{
                                $scope.isPrompt(json.message);
                            }
                        })
                    }

                }

            }
        };


        //请求活动图片列表
        function activityImglist() {
            $http({
                method:'POST',
                url : $config.host+'/api/events/GetEventPhoto',
                params:{
                    nEventId : $scope.coverImg.listId,
                    nCurPage : $scope.imgPage.page,
                    nPageSize : $scope.imgPage.size
                }
            }).success(function (json) {
                if(json.isSuccess&&json.data){
                    $scope.actdatas = json.data;
                    //重新赋值分页信息
                    $scope.imgPage.total = json.nTotal;
                    $scope.imgPage.change = function (value) {
                        $scope.imgPage.page = value;
                        activityImglist();
                    }

                }else{
                    $scope.actdatas = false;
                }
            })
        };

        //请求封面图片列表
        function coverImglist() {
            $http({
                method:'POST',
                url : $config.host+'/api/events/GetCoverPhoto',
                params:{
                    nEventId : $scope.coverImg.listId,
                    nCurPage : $scope.imgPage.page,
                    nPageSize : $scope.imgPage.size
                }
            }).success(function (json) {
                console.log(json.data);
                if(json.isSuccess&&json.data){
                    $scope.covdatas = json.data;
                    //重新赋值分页信息
                    $scope.imgPage.total = json.nTotal;
                    $scope.imgPage.change = function (value) {
                        $scope.imgPage.page = value;
                        coverImglist();
                    }
                }else{
                    $scope.covdatas = false;
                }
            })
        }


        //图片裁剪功能
        function cropImgInit() {
            $scope.cropImg =  {
                isShow: false,
                myButtonLabels: {
                    rotateLeft: '左翻转',
                    rotateRight: '右翻转',
                    zoomIn: '放大',
                    zoomOut: '缩小',
                    fit: '自适应',
                    crop: '剪裁'
                },
                updateResultImage: function (base64) {
                    $scope.cropImg.imgResult = base64;
                    $scope.$apply(); // Apply the changes.
                },
                getCropperApi: function (api) {
                    api.zoomIn(2);
                    api.zoomOut(2);
                    api.rotate(360);
                    api.fit();
                    $scope.cropImg.imgResult = api.crop();
                },
                close: function () {
                    //关闭裁剪的弹出框
                    $scope.cropImgOpen.close();
                },
                //点击保存按钮
                save: function () {
                    this.close();
                    // 这里写的上传逻辑
                    console.log($scope.coverImg.type);
                    if($scope.coverImg.type == 'act'){
                        console.log('hhhh');
                        //上传活动图片
                        $http({
                            method:'POST',
                            url : $config.host+'/api/events/UploadEventPhotoInBack',
                            headers:{
                                UID :getCookie('nUserId'),
                                TOKENID : getCookie('strTokenId')
                            },
                            data: $config.urlCode({
                                EventId : $scope.coverImg.listId,
                                'files[0].filekey' : 'file1',
                                'files[0].fileContent' : $scope.cropImg.imgResult
                            })
                        }).success(function (json) {
                            //图片上传成功
                            if(json.isSuccess){
                                // 刷新列表
                                activityImglist();
                            }else{
                                $scope.isPrompt(json.message);
                            }
                        })
                    }
                    else if($scope.coverImg.type == 'cov'){
                        //上传封面图片
                        $http({
                            method:'POST',
                            url : $config.host+'/api/events/UploadCoverPhotoInBack',
                            headers:{
                                UID :getCookie('nUserId'),
                                TOKENID : getCookie('strTokenId')
                            },
                            data: $config.urlCode({
                                EventId : $scope.coverImg.listId,
                                'files[0].filekey' : 'file1',
                                'files[0].fileContent' : $scope.cropImg.imgResult
                            })
                        }).success(function (json) {
                            //图片上传成功
                            if(json.isSuccess){
                                // 刷新列表
                                coverImglist();
                            }else{
                                $scope.isPrompt(json.message);
                            }
                        })
                    }

                }
            }
        }

    }


    //页面过滤器
    angular.module('BlurAdmin.pages.active')
        //过滤详情内容
        .filter('activeTextFilter', function () {
            return function (value) {
                var num = 30;
                if(!value) return '';
                if(value.length<num){
                    return value;
                }else{
                    return value.substring(0,num)+'...';
                }
            }
        })

})();